package org.itboys.mobile.service.mongo.weixin;

import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.activity.SundayActivityDetailDto;
import org.itboys.mobile.dto.activity.SundayActivityDto;
import org.itboys.mobile.entity.mongo.SundayActivity;
import org.itboys.mobile.entity.mongo.SundayApply;
import org.itboys.mobile.entity.mongo.SundayCollection;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author：贾琦磊
 * @Date：2018/7/11
 * @Description：【微信小程序】活动相关
 */
@Service
public class SundayWeiXinActivityService extends BaseMongoService<SundayActivity>{
    @Resource(name = "mobileDs")
    private MongoDataSource DataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return DataSource;
    }

    @Override
    protected Class<SundayActivity> getEntityClass() {
        return SundayActivity.class;
    }
    @Autowired
    private SundayWeiXinCollectionService collectionService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayWeiXinApplyService applyService;
    @Autowired
    private SundayWeiXinActivityRelatedService relationService;



    /**
     * 查询活动列表|用户收藏活动|已报名活动
     * @param request
     * @param memberId
     * @param isApply
     * @return
     * @throws ParseException
     */
    public List<SundayActivityDto> select(HttpServletRequest request,Long memberId,Integer isApply,Integer isRecommend) throws ParseException {
        List<SundayActivityDto> result=new ArrayList<>();
        Map<String,Object> param= ParamUtil.packageMongoExactParam(request);
        Map _param=new HashMap();
        _param.put("isDeleted", SundayCommonConstants.NO);
        param.put("isDeleted", SundayCommonConstants.NO);
        if(isRecommend!=null&&isRecommend==1){
            param.put("isRecommend",SundayCommonConstants.YES);
        }
        Set<Long> ids=new HashSet<>();
        /**
         * 如果查询已经报名的活动，先查询报名表组装用户报名活动的id集合
         */
        if(SundayCommonConstants.YES.equals(isApply)){
            _param.put("memberId",memberId);
            List<SundayApply> applies = applyService.list(_param);
            if(ListUtil.isNotNull(applies)){
                for (SundayApply apply:applies ) {
                    ids.add(apply.getActivityId());
                }
            }
            param.put("id in",ids);
        }


        List<SundayActivity> sundayActivities = super.pageQuery(request,param).getData();
        if(!ListUtil.isNotNull(sundayActivities)){

            return result;
        }
        for (SundayActivity activity:sundayActivities ) {
            ids.add(activity.getId());
        }
        /**
         * 查询与活动相关相关报名数据
         */
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);
        List<SundayApply> applies = applyService.list(param);
        /**
         * 查询出用户收藏的为未被删除的活动，ids缩小查询数据量
         */
        List<SundayCollection> collections = collectionService.select(ids,SundayCommonConstants.collect_type_activity);
        /**
         * 获取活动被收藏次数、热度
         */
        for (SundayActivity activity:sundayActivities){
            int collectionNum=0;
            for (SundayCollection collection:collections) {
                if(collection.getOtherId().equals(activity.getId())){
                    collectionNum+=1;
                }
            }
            activity.setHot(collectionNum);
        }
        result= packageDtos(sundayActivities, applies, collections,memberId);
        return result;
    }

    /**
     * 封装返回数据类型dto
     * @param activities
     * @param applies
     * @param collections
     * @return
     * @throws ParseException
     */
    public List<SundayActivityDto> packageDtos(List<SundayActivity> activities,List<SundayApply> applies,List<SundayCollection> collections,Long memberId) throws ParseException {
        //定义返回值集合
        List<SundayActivityDto> result=new ArrayList<>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date today=new Date();
        for (SundayActivity activity:activities){
            SundayActivityDto dto=new SundayActivityDto();
            dto.setId(activity.getId());
            dto.setName(activity.getName());
            dto.setSlogan(activity.getSlogan());
            dto.setDate(activity.getsDate().substring(5,10)+"至"+activity.geteDate().substring(5,10));
            dto.setImage(resourceHolder.getStringValue("imgRoot")+activity.getImage());
            dto.setBackImage(resourceHolder.getStringValue("imgRoot")+activity.getBackImage());
            dto.setHeadImage(resourceHolder.getStringValue("imgRoot")+activity.getHeadImage());
            dto.setIsRecommend(activity.getIsRecommend());
            dto.setHot(activity.getHot());
            //判断活动是否结束
            Date eDate = sdf.parse(activity.geteDate());
            dto.setIsOver(eDate.getTime()>today.getTime()?SundayCommonConstants.NO:SundayCommonConstants.YES);
            //判断活动用户是否报名
            for (SundayApply apply:applies) {
                if(apply.getActivityId().longValue()==activity.getId()){
                    dto.setIsApply(SundayCommonConstants.YES);
                    break;
                }
            }
            //判断用户是否收藏
            for (SundayCollection collection:collections){
                if(collection.getOtherId().equals(activity.getId())&&collection.getMemberId().equals(memberId)){
                    dto.setIsCollect(SundayCommonConstants.YES);
                    break;
                }
            }
            if(dto.getIsApply()==null){dto.setIsApply(SundayCommonConstants.NO);}
            if(dto.getIsCollect()==null){dto.setIsCollect(SundayCommonConstants.NO);}
            result.add(dto);
        }
        return result;
    }

    /**
     * 小程序获取活动详情
     * @param activityId
     * @return
     */
    public SundayActivityDetailDto findOne(Long memberId,Long activityId) throws ParseException {
        SundayActivityDetailDto result=new SundayActivityDetailDto();
        SundayActivity activity = super.getById(activityId);
        if(activity==null){
            return result;
        }
        result = packageDetailDto(memberId, activity);
        /**
         * 设置活动相关内容
         */
        result.setRelateds(relationService.select(activityId));
        return result;
    }

    /**
     * 拼装详情dto
     * @param memberId
     * @param activity
     * @return
     */
    public SundayActivityDetailDto packageDetailDto(Long memberId,SundayActivity activity) throws ParseException {
        SundayActivityDetailDto result=new SundayActivityDetailDto();
        if(activity==null){return result;}
        result.setImage(resourceHolder.getStringValue("imgRoot")+activity.getImage());
        result.setName(activity.getName());
        result.setRecommend(activity.getRecommend());
        result.setDate(activity.getsDate()+"至"+activity.geteDate());
        result.setDetail(activity.getDesc());
        result.setSlogan(activity.getSlogan());
        //判断用户是否关注
        Map<String,Object> param=new HashMap();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);
        param.put("otherId",activity.getId());
        param.put("type",SundayCommonConstants.collect_type_activity);
        List<SundayCollection> collections = collectionService.list(param);
        result.setIsCollect(ListUtil.isNotNull(collections)?SundayCommonConstants.YES:SundayCommonConstants.NO);
        //判断用户是否报名
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);
        param.put("activityId",activity.getId());
        List<SundayApply> applies = applyService.list(param);

        result.setIsApply(ListUtil.isNotNull(applies)?SundayCommonConstants.YES:SundayCommonConstants.NO);

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date today=new Date();
        Date eDate = sdf.parse(activity.geteDate());
        result.setIsOver(eDate.getTime()>today.getTime()?SundayCommonConstants.NO:SundayCommonConstants.YES);

        return  result;
    }
}
